﻿using GKQC.Common;
using GKQC.DbHelper.Dao;
using GKQC.DbHelper.DbModels;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms;

namespace GKQC.DbHelper.Services
{
    public class SysLogService
    {
        /// <summary>
        /// 操作日志
        /// </summary>
        /// <param name="dbContext"></param>
        /// <param name="user"></param>
        /// <param name="form"></param>
        /// <param name="type">动作类型描述：新增/修改/浏览/审核等</param>
        /// <param name="pkValue">单号或主键</param>
        /// <param name="data">操作的数据，一般删除才要</param>
        public static void Log(AllDbContext dbContext, UserModel user, Form form, string type, string pkValue, object data)
        {
            try
            {
                LogModel model = new LogModel();
                model.UserCode = user.UserCode;
                model.UserName = user.UserName;
                model.FormCode = form.Name;
                model.FormName = form.Text;
                if (type.Contains("("))
                    type = type.Substring(0, type.IndexOf('('));
                model.Type = type;
                model.LogType = "0";
                model.PkValue = pkValue;
                string dataJson = string.Empty;
                if (data !=null) dataJson = JsonHelper.ToJson(data);
                model.Data = dataJson;
                model.Time = user.GetServerTime();
                model.HostName = Dns.GetHostName();
                dbContext.QcDb.Insertable<LogModel>(model).ExecuteCommand();

            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }
        }

        public static int DelLog(AllDbContext dbContext, List<int> Ids)
        {
            try
            {
                return dbContext.QcDb.Deleteable<LogModel>().In(Ids.ToArray()).ExecuteCommand();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            return 0;
        }

        public static List<LogModel> QueryLog(AllDbContext dbContext, DateTime startDate, DateTime endDate, string usercode)
        {
            try
            {
                return dbContext.QcDb.Queryable<LogModel>().Where(it => it.UserCode == usercode && it.Time > startDate && it.Time < endDate).ToList();
            }
            catch (Exception ex)
            {
                Logger.LogError(ex);
            }

            return null;
        }
    }
}